package com.control.qct.businesssteward.httputils;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.text.TextUtils;
import android.util.Log;

import com.control.qct.businesssteward.base.BaseBean;
import com.control.qct.businesssteward.base.BaseFragment;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.internal.$Gson$Types;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.PostRequest;

import org.json.JSONObject;

import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Map;

/**
 * 网络请求类
 * Created by Administrator on 2018/1/30 0030.
 */

public class HttpUtils {
    private ProgressDialog mProgressDialog;
    private Context mContext;
    private Gson mGson;
    private BaseBean mBaseBean;

    public HttpUtils(ProgressDialog progressDialog, Context context) {
        mGson = new Gson();
        this.mContext = context;
        this.mProgressDialog = progressDialog;
        showDialog();
    }

    public HttpUtils(ProgressDialog progressDialog, BaseFragment context) {
        mGson = new Gson();
        this.mContext = context.getContext();
        this.mProgressDialog = progressDialog;
        showDialog();
    }

    public HttpUtils(ProgressDialog progressDialog, Context context, boolean isShow) {
        mGson = new Gson();
        this.mContext = context;
        this.mProgressDialog = progressDialog;
        if (isShow) {
            showDialog();
        }
    }

    public HttpUtils(ProgressDialog progressDialog, BaseFragment context, boolean isShow) {
        mGson = new Gson();
        this.mContext = context.getContext();
        this.mProgressDialog = progressDialog;
        if (isShow) {
            showDialog();
        }
    }

    /**
     * 异步POST JSON请求
     */
    public void postToJson(final RequestConfig config, final IHttpResult httpResult) {
        mBaseBean = new BaseBean();
        if (!isNetActive(mContext)) {
            mBaseBean.setMessage("网络异常");
        }
        OkGo.<String>post(config.getWebAddress()).tag(mContext).cacheKey(config.getCacheKey()).cacheMode(config
                .getCacheMode()).cacheTime(10000).headers(config.getHeaders()).upJson(config.getParams() == null ?
                config.getBody() : new JSONObject(config.getParams()).toString()).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    closeDialog();
                    mBaseBean = parseData(response.body(), config);
                    if (mBaseBean.isSuccessed()) {
                        httpResult.onSuccess(mBaseBean);
                    } else if (!TextUtils.isEmpty(mBaseBean.getMessage())) {
                        if (mBaseBean.getMessage().contains("token不存在或已过期")) {//判断token是否过期
                            //token过期--发送广播
                            Intent intent = new Intent("com.control.qct.business_steward.FORCE_OFFLINE");
                            mContext.sendBroadcast(intent);
                            return;
                        }
                        httpResult.onFail(mBaseBean);
                    }
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                    mBaseBean.setMessage("数据格式错误");
                    httpResult.onFail(mBaseBean);
                } catch (Exception e) {
                    e.printStackTrace();
                    mBaseBean.setMessage("数据错误");
                    httpResult.onFail(mBaseBean);
                }
            }

            @Override
            public void onError(Response<String> response) {
                mBaseBean.setMessage("服务器繁忙，请稍后再试！");
                httpResult.onFail(mBaseBean);
                closeDialog();
            }
        });
    }

    /**
     * 异步POST键值对请求接口
     */
    public void postFromData(final RequestConfig config, final IHttpResult httpResult) {
        mBaseBean = new BaseBean();
        if (!isNetActive(mContext)) {
            mBaseBean.setMessage("网络异常");
        }
        PostRequest<String> request = OkGo.<String>post(config.getWebAddress()).tag(mContext).headers(config
                .getHeaders()).params(config.getParams()).isMultipart(true);
        if (config.getFile() != null && config.getFile().size() > 0) {
            for (Map.Entry<String, File> file : config.getFile().entrySet()) {
                request.params(file.getKey(), file.getValue());
            }
        }
        request.execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    closeDialog();
                    mBaseBean = parseData(response.body(), config);
                    if (mBaseBean.isSuccessed()) {
                        httpResult.onSuccess(mBaseBean);
                    } else if (!TextUtils.isEmpty(mBaseBean.getMessage())) {
                        if (mBaseBean.getMessage().contains("token不存在或已过期")) {//判断token是否过期
                            //token过期--发送广播
                            Intent intent = new Intent("com.control.qct.business_steward.FORCE_OFFLINE");
                            mContext.sendBroadcast(intent);
                            return;
                        }
                        httpResult.onFail(mBaseBean);
                    }
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                    mBaseBean.setMessage("数据格式错误");
                    httpResult.onFail(mBaseBean);
                } catch (Exception e) {
                    e.printStackTrace();
                    mBaseBean.setMessage("数据错误");
                    httpResult.onFail(mBaseBean);
                }
            }

            @Override
            public void onError(Response<String> response) {
                mBaseBean.setMessage("服务器繁忙，请稍后再试！");
                httpResult.onFail(mBaseBean);
                closeDialog();
            }
        });
    }

    /**
     * 异步GET请求
     */
    public void getToJson(final RequestConfig config, final IHttpResult httpResult) {
        mBaseBean = new BaseBean();
        if (!isNetActive(mContext)) {
            mBaseBean.setMessage("网络异常");
        }
        OkGo.<String>get(config.getWebAddress()).cacheKey(config.getCacheKey()).cacheMode(config.getCacheMode())
                .cacheTime(10000).tag(mContext).params(config.getParams()).headers(config.getHeaders())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            closeDialog();
                            mBaseBean = parseData(response.body(), config);
                            if (mBaseBean.isSuccessed()) {
                                httpResult.onSuccess(mBaseBean);
                            } else if (!TextUtils.isEmpty(mBaseBean.getMessage())) {
                                if (mBaseBean.getMessage().contains("token不存在或已过期")) {//判断token是否过期
                                    //token过期--发送广播
                                    Intent intent = new Intent("com.control.qct.business_steward.FORCE_OFFLINE");
                                    mContext.sendBroadcast(intent);
                                    return;
                                }
                                httpResult.onFail(mBaseBean);
                            }
                        } catch (JsonSyntaxException e) {
                            e.printStackTrace();
                            mBaseBean.setMessage("数据格式错误");
                            httpResult.onFail(mBaseBean);
                        } catch (Exception e) {
                            e.printStackTrace();
                            mBaseBean.setMessage("数据错误");
                            httpResult.onFail(mBaseBean);
                        }
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        try {
                            closeDialog();
                            mBaseBean = parseData(response.body(), config);
                            if (mBaseBean.isSuccessed()) {
                                httpResult.onSuccess(mBaseBean);
                            } else if (!TextUtils.isEmpty(mBaseBean.getMessage())) {
                                if (mBaseBean.getMessage().contains("token不存在或已过期")) {//判断token是否过期
                                    //token过期--发送广播
                                    Intent intent = new Intent("com.control.qct.business_steward.FORCE_OFFLINE");
                                    mContext.sendBroadcast(intent);
                                    return;
                                }
                                httpResult.onFail(mBaseBean);
                            }
                        } catch (JsonSyntaxException e) {
                            e.printStackTrace();
                            mBaseBean.setMessage("数据格式错误");
                            httpResult.onFail(mBaseBean);
                        } catch (Exception e) {
                            e.printStackTrace();
                            mBaseBean.setMessage("数据错误");
                            httpResult.onFail(mBaseBean);
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        mBaseBean.setMessage("服务器繁忙，请稍后再试！");
                        httpResult.onFail(mBaseBean);
                        closeDialog();
                    }
                });
    }

    /**
     * 解析泛型返回baseBean基类
     *
     * @param data
     * @param config
     * @return
     */
    private BaseBean parseData(String data, RequestConfig config) {
        BaseBean baseBean = mGson.fromJson(data, BaseBean.class);
        if (baseBean.isSuccessed()) {
            Type type;
            if (config.getCls() != null) {
                if (config.getCls().getName().equals(ArrayList.class.getName())) {
                    type = $Gson$Types.newParameterizedTypeWithOwner(null, BaseBean
                            .class, $Gson$Types.newParameterizedTypeWithOwner(null,
                            config.getCls(), config.getElement()));
                } else {
                    type = $Gson$Types.newParameterizedTypeWithOwner(null, BaseBean
                            .class, config.getCls());
                }
                return mGson.fromJson(data, type);
            } else {
                if (config.getElement() != null) {
                    type = $Gson$Types.newParameterizedTypeWithOwner(null, BaseBean.class,
                            $Gson$Types.newParameterizedTypeWithOwner(null, ArrayList
                                    .class, config.getElement()));
                    return mGson.fromJson(data, type);
                }
            }
        }
        return baseBean;
    }

    private void showDialog() {
        if (mProgressDialog != null) {
            mProgressDialog.show();
        }
    }

    /**
     * 关闭dialog
     */
    private void closeDialog() {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
    }

    // 是否有网络，包括2g,3g.wifi
    @SuppressLint("MissingPermission")
    public static boolean isNetActive(Context context) {
        boolean flag = false;
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (manager.getActiveNetworkInfo() != null) {
            flag = manager.getActiveNetworkInfo().isAvailable();
        }
        return flag;
    }

    public interface IHttpResult {
        void onSuccess(BaseBean baseBean);

        void onFail(BaseBean baseBean);
    }
}
